import type { ConfigEnv, UserConfig } from 'vite';
import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';
import Components from 'unplugin-vue-components/vite';
import AutoImport from 'unplugin-auto-import/vite';
import UnoCSS from 'unocss/vite';
import { presetUno } from 'unocss';
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers';
import dynamicImport from 'vite-plugin-dynamic-import';

// https://vitejs.dev/config/
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  return {
    define: {
      'process.env.VITE_TC_BASE_URL': JSON.stringify(env.VITE_TC_BASE_URL),
      'process.env.VITE_TC_DEV_TOKEN': JSON.stringify(env.VITE_TC_DEV_TOKEN),
      'process.env.VUE_APP_PUBLIC_PATH': JSON.stringify(env.VITE_APP_PUBLIC_PATH),
    },
    plugins: [
      vue(),
      UnoCSS({
        presets: [presetUno()],
      }),
      Components({
        resolvers: [AntDesignVueResolver()],
      }),
      AutoImport({
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/, // .vue
        ],
        imports: [
          'vue',
          'vue-router',
          {
            '@vueuse/core': [
              // named imports
              'useMouse', // import { useMouse } from '@vueuse/core',
            ],
          },
        ],
        // 在模板中使用会用到。设置 true，auto-imports.d.ts会生成对应的ComponentCustomProperties，可以避免ts的报错
        vueTemplate: true,
        eslintrc: {
          enabled: true, // 开启后，自动生成对应的声明文件
          filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
          globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
        },
      }),
      dynamicImport(/* options */),
    ],
    resolve: {
      alias: {
        '@': path.join(__dirname, './src'),
      },
    },
    server: {
      host: true,
      port: 3000,
      proxy: {
        '/api': {
          target: env.VITE_TC_BASE_URL,
        },
      },
    },
  };
});
